<template>
  <div>
    <!-- <q-btn :class="readOnly? 'grey-btn bg-green':'grey-btn'" :disable="readOnly" @click="clickBtn">Job Complete</q-btn> -->
    <q-dialog  v-model="checkTestResultDiag"> 
      <my-dialog title="Notice" content="Test result is not completed in final check" :cancel="()=>checkTestResultDiag= false" :submit="()=>$emit('redirectToFinalCheck')" :label="'Go to final check'"></my-dialog>
    </q-dialog>
    <order-tab-container
      :btn1-callback="complete"
      label1="Endorse As Current User"
      color1="bg-green-4"
      :btn2-callback="openChooseDiag"
      label2="Endorse As Other User"
      color2="bg-blue-4"
      :disable="readOnly"
    >
      <q-card class="q-ma-sm">
        <q-card-section class="bg-yellow-9 fal items-center">
          <q-icon size="2rem" name="warning_amber"></q-icon>
          <div class="text-h6 q-ml-md">Job Complete</div>
        </q-card-section>

        <q-card-section>
          {{ isCompleteTestResult }}
          <div class="text-body">
            <template v-if="isOutstanding">
              <div class="text-h6">
                The tasks are not all passed / completed.
              </div>
              <template v-for="(item, index) in checkStatus" :key="index">
                <div v-if="item.outstanding">
                  <span class="text-h6 cap">{{ parseTitle(index, true) }}</span>
                  <ul>
                    <li v-for="(m, i) in item.message" :key="i">
                      {{ m }}
                    </li>
                  </ul>
                </div>
              </template>
            </template>
            <template v-else>
              All pass
            </template>
            <span v-if="!isReadOnly">
              Are you sure to complete the job?
              <br />
              Allow check out for the equipment?
            </span>
           
          </div>
        </q-card-section>

        <q-card-section>
          <div v-if="isOutstanding&&!isReadOnly">
            <q-checkbox
              :disable="readOnly"
              v-model="force"
              label="Force Complete"
            />
          </div>
        </q-card-section>
      </q-card>
    </order-tab-container>

    <q-dialog  v-model="chooseDiag" >
      <my-dialog title="Authenticate Method">
        <q-card>
          <!-- <q-toolbar class="bg-primary text-white">
            <q-toolbar-title> Choose Authenticate Method </q-toolbar-title>
            <q-btn flat round dense icon="close" v-close-popup />
          </q-toolbar> -->
        <q-card-section class="row items-center justify-evenly">
          <q-btn
            class="default-btn"
            label="Use Password"
            @click="openPasswordDiag"
            />
            <q-btn             
              class="default-btn"
              label="Scan QRCode" 
              @click="openCamDiag" />
          </q-card-section>
        </q-card>
      </my-dialog>
    </q-dialog>

    <q-dialog  v-model="camDiag" >
      <open-cam @submit="endoresOtherUser" v-if="camDiag"></open-cam>
    </q-dialog>

    <q-dialog v-model="passwordDiag" >
      <MyDialog title="Password">
        <q-card>
          <!-- <q-toolbar class="bg-primary text-white">
            <q-toolbar-title> Password Authenticate </q-toolbar-title>
            <q-btn flat round dense icon="close" v-close-popup />
          </q-toolbar> -->
          <q-card-section class="q-gutter-md">
            <q-input class="input-css" v-model="username" type="text" label="Username" borderless />
          <q-input class="input-css" v-model="password" type="password" label="Password" borderless />
        </q-card-section>
        <q-card-actions vertical align="center">
          <q-btn
            class="default-btn"
            @click="passwordComplete"
            flat
            label="Submit"
          />
        </q-card-actions>
      </q-card>
    </MyDialog>
    </q-dialog>
  </div>
</template>

<script lang="ts" setup>
import {
  getCheckStatus,
  getOrderDetail,
  jobComplete,
} from 'src/services/repairService';
import { RepairOrderCheckStatus } from 'src/services/type';
import { computed, onMounted, ref } from 'vue';
import { parseTitle } from 'src/utils/stringUtils';
import { useQuasar } from 'quasar';
import OpenCam from '../OpenCam.vue';
import OrderTabContainer from '../container/OrderTabContainer.vue';
import MyDialog from '../container/MyDialog.vue';
import {
  Loading,

  // optional!, for example below
  // with custom spinner
  QSpinnerGears
} from 'quasar'
/* const props = defineProps({
    orderId: {
        type: Number,
        required: true,
    },
    isReadOnly:{
        type: Boolean ,
        required: true,
    }
}) */

const props = defineProps<{
  orderId: number;
  isReadOnly: boolean
}>();

const chooseDiag = ref(false);
const camDiag = ref(false);
const passwordDiag = ref(false);
const username = ref('');
const password = ref('');

const readOnly = ref(false);

const order = ref();

const q = useQuasar();

const emit = defineEmits(['update', 'afterJobComplete', 'redirectToFinalCheck']);

const checkStatus = ref<RepairOrderCheckStatus>();

const diag = ref(false);

const force = ref(false);

const checkTestResultDiag = ref(false);


const isOutstanding = computed(() => {
  let outstanding = 0;
  if (checkStatus.value) {
    for (const key in checkStatus.value) {
      if (key == 'fail_part') continue
      if (Object.prototype.hasOwnProperty.call(checkStatus.value, key)) {
        
        const element = checkStatus.value[key as keyof RepairOrderCheckStatus];
        outstanding += element.outstanding;
      }
    }
  }
  return outstanding;
});

const isCompleteTestResult = computed(() => {
  let outstanding = 0;
  if (checkStatus.value) {
    for (const key in checkStatus.value) {
      if (key !== 'test_result') continue
      if (Object.prototype.hasOwnProperty.call(checkStatus.value, key)) {
        const element = checkStatus.value[key as keyof RepairOrderCheckStatus];
        outstanding += element.outstanding;
      }
    }
  }
  return outstanding;
});

async function init() {
  getCheckStatus(props.orderId).then((data) => {
    checkStatus.value = data;
    emit('update', data);
  });

  const res = await getOrderDetail(props.orderId);
  if (res.data) {
    if (
      res.data.status == 'COMPLETE' ||
      res.data.status == 'COMPLETE*' ||
      res.data.status == 'CHECKOUT'
    ) {
      readOnly.value = true;
    }
  }
  
}

init();

async function clickBtn() {
  await init();
  diag.value = true;
}


async function complete(
  qrcode: string | null = null,
  username: string | null = null,
  password: string | null = null
) {

  if (isCompleteTestResult.value>0){
    checkTestResultDiag.value = true
    return
  }

  Loading.show()
  
  const res = await jobComplete(
    props.orderId,
    force.value,
    qrcode,
    username,
    password
  );
  Loading.hide()
  
  if (res.data.code == 0) {
    q.notify({
      message: res.data.message,
      color: 'negative',
      icon: 'warning',
      actions: [{ label: 'Dismiss', color: 'white' }],
      timeout: 0,
    });
    res.data.data.forEach((message: string) => {
      q.notify({
        message: message,
        color: 'negative',
        icon: 'warning',
        actions: [{ label: 'Dismiss', color: 'white' }],
        timeout: 0,
      });
    });
    return false;
  }
  if (res.data.code == 1) {
    q.notify({
      message: res.data.message,
      color: 'positive',
      icon: 'check',
      actions: [{ label: 'Dismiss', color: 'white' }],
      timeout: 1000,
    });
    diag.value = false;
    emit('afterJobComplete');
    readOnly.value = true;
    return true;
  }

}

function endoresCurrentUser() {
  return;
}

function endoresOtherUser(v: string) {
  complete(v);
  camDiag.value = false;
}

function openChooseDiag() {
  chooseDiag.value = true;
  camDiag.value = false;
  passwordDiag.value = false;
}

function openCamDiag() {
  chooseDiag.value = false;
  camDiag.value = true;
  passwordDiag.value = false;
}

function openPasswordDiag() {
  chooseDiag.value = false;
  camDiag.value = false;
  passwordDiag.value = true;
}

async function passwordComplete() {
  const res = await complete(null, username.value, password.value);
  if (res) passwordDiag.value = false;
}
</script>
